package com.wocai.jrt.orgadmin.fundmanager.action;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.common.PropUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.fundmanager.model.FundManager;
import com.wocai.jrt.orgadmin.fundmanager.service.spi.FundManagerService;
import com.wocai.jrt.orgadmin.investor.bean.ResultBean;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 基金经理控制器
 * @author yinlei
 * @date 2015-10-28 15:18:52
 */
@Controller
@RequestMapping("/fundManager")
public class FundManagerAction extends GenericAction<FundManager> {
	private static final Logger LOGGER = LoggerFactory.getLogger(FundManagerAction.class);

	public static final String IMAGES_URL = PropUtils.get("images.url");
	@Inject
	private FundManagerService fundManagerServiceImpl;
	
	/**
     * 获得基金经理List，初始化列表页。
     * @param model 参数
     * @return 基金经理List
     */
	@RequestMapping("/list")
	public String list(FundManager model, Map<String, Object> maps) {
		try {
			LOGGER.info("query list param: [{}]",JSON.toJSONString(model));
//			List<FundManager> list = fundManagerServiceImpl.pagedList(model);
//			maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "fundManager/list";
	}
	
	/**
	 * 获得基金经理List，Json格式。
	 * @param model 参数
	 * @return 基金经理List
	 */
	@ResponseBody
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public Map<String, Object> query(@RequestBody FundManager model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrderBy("fund_number desc");
			model.setOrgId(UserUtils.getOrgId());
			List<FundManager> list = fundManagerServiceImpl.getFundManagerList(model);
			LOGGER.info("query adout list param: [{}]",JSON.toJSONString(model));
			// 统计的时候，不需要分页
			model.setStart(null);
			long totalRecord = fundManagerServiceImpl.getCountByOrgId(model);

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("about query success.");
			}

			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("about query error, msg=[{}]", e.getMessage());
		}
		return result;
	}
	
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add(Map<String, Object> maps) {
    	maps.put("fundManagerId", ObjectId.get().toString());
        return "fundManager/add";
    }
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody @Valid FundManager model, BindingResult errors) {
    	JsonBean bean = new JsonBean();
    	try {
    		if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("参数错误");
				return bean;
			}
			String mobile = model.getMobile();
			if (!Pattern.compile("^[1][3,4,5,8][0-9]{9}$").matcher(mobile).matches() && !Pattern.compile("[0]{1}[0-9]{2,3}[0-9]{7,8}$").matcher(mobile).matches()) {
				bean.setCode(0);
				bean.setMessage("联系电话输入有误！");
				return bean;
			}
			// 获取机构代码
			String orgId = UserUtils.getOrgId();
			model.setOrgId(orgId);
			model.setDeleted(false);
			model.setCreateTime(new Date());
			model.setFundNumber(0);
    		int result = fundManagerServiceImpl.save(model);
            if (result == 1) {
                bean.setMessage("新增基金经理成功！");
                bean.setCode(1);
                LOGGER.info("save record success.");
            } else {
                bean.setMessage("oh,no,服务器偷了个小懒！");
                LOGGER.error("save record error.");
            }
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 查看基金经理详情页。
     * @param model 查询参数，携带ID
     * @return 基金经理详情页
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
    	FundManager model = null;
    	try {
    		LOGGER.info("query adout detail param: [{}]",JSON.toJSONString(id));
    		model = fundManagerServiceImpl.get(id);
            maps.put("fundManager", model);//将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "fundManager/detail";
    }
    
    /**
     * 跳转到编辑信息页面
     * @param model 查询参数，携带ID
     * @return 编辑页面
     */
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
    	FundManager model = null;
        try {
			model = fundManagerServiceImpl.get(id);
			maps.put("fundManager", model);
		} catch (Exception e) {
			LOGGER.error("query record edit, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "fundManager/edit";
    }
    
    /**
     * 更新基金经理信息
     * @param model 要更新的基金经理信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody @Valid FundManager model, BindingResult errors) {
    	JsonBean bean = new JsonBean();
		try {
			if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("输入参数错误");
				return bean;
			}
			int result = fundManagerServiceImpl.updateById(model);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("基金经理修改成功！");
			} else {
				bean.setCode(0);
				bean.setMessage("基金经理修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("doEdit Investor list error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(e.getMessage());
		}
		return bean;
    }
    
    /**
     * 删除基金经理信息
     * @param model 要更新的基金经理信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/delete")
    public JsonBean delete(String id) {
    	JsonBean bean = new JsonBean();
		try {
			FundManager fund = fundManagerServiceImpl.get(id);
			
			try {
				// 删除头像
				String oldPath = IMAGES_URL+fund.getAvatar();
				File files = new File(oldPath);
				MyFileUtils.deleteFileDir(files);
				files.delete();
			} catch (Exception e) {
				LOGGER.error("delete FundManager error, errorMsg=[{}].", e.getMessage());
			}
			int result = fundManagerServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("基金经理删除成功！");
			} else {
				bean.setCode(0);
				bean.setMessage("基金经理删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("delete FundManager error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(e.getMessage());
		}
		return bean;
    }
    
	/**
	 * 投资人头像新增上传
	 * 
	 * @param id
	 *            参数id
	 * @return 投资人实体
	 */
	@ResponseBody
	@RequestMapping("/avatarnew")
	public ResultBean avatarnew(@RequestParam("__avatar1") MultipartFile file,
			@RequestParam("id") String id) {
		ResultBean result = new ResultBean();
		try {
			// 判断文件大小
			if (file.getSize() > (1024 * 1024 * 1024 * 2L)) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像文件不能大于2M！");
				return result;
			}
			LOGGER.info("request file upload, filename=[{}]", file.getOriginalFilename());
			// 上传头像
			String filePath = MyFileUtils.uploadImg(file,ImgType.values()[9],".jpeg");
			FundManager manager = new FundManager();
			manager.setId(id);
			manager.setAvatar(filePath);
			int i = fundManagerServiceImpl.updateById(manager);
			if (i != 1) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像保存出错！");
				// 删除当前保存的头像
				filePath =IMAGES_URL+ filePath;
				File files = new File(filePath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
				return result;
			}
			LOGGER.info("upload file success, filePath=[{}]", filePath);
			// 封装result
			result.setCode(5);
			result.setType(0);
			result.setSuccess(true);
			result.setSourceUrl(filePath);
			result.setMsg("upload file success");
			// JSON.toJSONString(jsonBean);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			result.setCode(5);
			result.setType(3);
			result.setSuccess(false);
			result.setMsg("upload file error");
		}
		return result;
	}

	/**
	 * 投资人头像修改上传
	 * 
	 * @param id
	 *            参数id
	 * @return 投资人实体
	 */
	@ResponseBody
	@RequestMapping("/avatarup")
	public ResultBean avatarup(@RequestParam("__avatar1") MultipartFile file,
			@RequestParam("id") String id, @RequestParam("oldPath") String oldPath) {
		ResultBean result = new ResultBean();
		try {
			// 判断文件大小
			if (file.getSize() > (1024 * 1024 * 1024 * 2L)) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像文件不能大于2M！");
				return result;
			}

			LOGGER.info("request file upload, filename=[{}]", file.getOriginalFilename());
			// 上传头像
			String filePath = MyFileUtils.uploadImg(file,ImgType.values()[9],".jpeg");
			FundManager manager = new FundManager();
			manager.setId(id);
			manager.setAvatar(filePath);
			int i = fundManagerServiceImpl.updateById(manager);
			if (i != 1) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像保存出错！");
				// 删除当前保存的头像
				filePath = filePath.substring(0, filePath.lastIndexOf("/"));
				File files = new File(filePath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
				return result;
			} else if (null != oldPath && !StringUtils.isBlank(oldPath)) {
				// 删除旧头像
				oldPath = IMAGES_URL+oldPath;
				File files = new File(oldPath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
			}
			LOGGER.info("upload file success, filePath=[{}]", filePath);
			// 封装result
			result.setCode(5);
			result.setType(0);
			result.setSuccess(true);
			result.setSourceUrl(filePath);
			result.setMsg("upload file success");
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			result.setCode(5);
			result.setType(3);
			result.setSuccess(false);
			result.setMsg("upload file error");
		}
		return result;
	}

	/***
	 * 下载头像img
	 * 
	 * @param path
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downImg")
	public JsonBean downImg(String path, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 发起请求的参数
			LOGGER.info("download img , url=[{}]", path);
			MyFileUtils.downloadFile(path, response);
			jsonBean.setCode(1);
			jsonBean.setMessage("下载头像成功!");
		} catch (Exception e) {
			LOGGER.error("download img error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("下载头像失败!");
		}
		return jsonBean;
	}

}
